<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/20/020
 * Time: 11:20
 */

namespace app\api\model;


use think\Exception;

class Brand extends BaseModel {


    /**
     * 创建或者编辑品牌
     * @param $param
     * @param $id
     * @return array|\think\response\Json
     */
    public static function createOrUpdateBrand($param, $id) {

        try {
            if ($id > 0) {

                $brand = self::get($id);
                if (!$brand) {
                    return json(['code' => 1, 'msg' => '品牌不存在']);
                }

                $check_name = self::where([['name', 'eq', $param['name']], ['id', 'neq', $id]])->find();
                if ($check_name) {
                    return ['code' => 1, 'msg' => '品牌名称已存在!'];
                }

                $brand->save($param);

            } else {
                $check_name = self::where([['name', 'eq', $param['name']]])->find();
                if ($check_name) {
                    return ['code' => 1, 'msg' => '品牌名称已存在!'];
                }

                self::create($param);
            }
            return ['code' => 0, 'msg' => '保存成功'];
        } catch (Exception $e) {
            return ['code' => 1, 'msg' => $e->getMessage()];
        }
    }
}